from PyQt4 import QtGui, QtCore
import os, random, gTile, gSystem
from gJson import loadString, loadInteger, loadObject, loadArray, loadCoordinates

class Troop(object):
    
    def __init__(self, rac="Human", num=1000, prof="Warriors", weap="Bronze Swords"):
        self.race = rac
        self.number = num
        self.profession = prof
        self.weapon = weap
        self._buffs = []
        
    def dumpToString(self):
        return "".join(["$t", "$r", self.race, "$n", str(self.number), "$p", self.profession, "$w", self.weapon])
        
    @staticmethod
    def loadFromString(stri):
        rac = stri[stri.find("$r")+2:stri.find("$n")]
        nu = int(stri[stri.find("$n")+2:stri.find("$p")])
        pro = stri[stri.find("$p")+2:stri.find("$w")]
        wea = stri[stri.find("$w")+2:]
        trop = Troop(rac, nu, pro, wea)
        return trop
    
    @staticmethod
    def loadMultFromString(stri):
        tmp = stri.split("$t")
        result = []
        for x in tmp:
            if x != "":
                result.append(Troop.loadFromString(x))
        return result

class Unit(object):
    
    def __init__(self, position, imgsrc, parent, startingTroops, owningfaction):
        self.ID = None
        self._position = position
        self._img = imgsrc
        self._moved = False
        self.createTile()
        self.troops = startingTroops
        self.commander = None
        self.currentTravelCounter = None
        self.movetarg = None
        self._game = parent
        self._owner = owningfaction
        self._movequeue = []
        self._buffs = []
                                                    
    def createTile(self):
        self.tile = gSystem.mainWindow.glwidget.createImage(os.path.join("data", "images", "units", self._img), gSystem.ARMY_LAYER, 
                                                    (0, 0, 31, 31), 
                                                    (self._position[0]*32, self._position[1]*32, 32, 32))
                                                    
    def setID(self, newid):
        self.ID = newid
        
    def advanceTurn(self):
        if self.currentTravelCounter:
            self.currentTravelCounter -= 1
            if self.currentTravelCounter <= 0:
                self.currentTravelCounter = None
                self._game.moveUnit(self, self.movetarg)
                self.movetarg = None
            
    def orderMove(self, targloc, targettype):
        self._movequeue = []
        self.currentTravelCounter = self.getTravelTime(targettype)
        self.movetarg = targloc
        self._movequeue.append(targloc)
        
    def changePosition(self, new):
        self._movequeue = []
        self.tile.destroy()
        self._position = (new[0], new[1])
        self.tile = gSystem.mainWindow.glwidget.createImage(os.path.join("data", "images", "units", self._img), gSystem.ARMY_LAYER, 
                                                    (0, 0, 31, 31), 
                                                    (self._position[0]*32, self._position[1]*32, 32, 32))
        
    def getTravelTime(self, targettype):
        if targettype == "Grassland":
            return 2
        elif targettype == "Forest":
            return 3
        return 5
    
    def canMove(self, loc, targettype):
        if ((self._position[0] == loc[0] and (self._position[1] == loc[1]-1 or self._position[1] == loc[1]+1)) or 
            (self._position[1] == loc[1] and (self._position[0] == loc[0]-1 or self._position[0] == loc[0]+1))):
            if targettype != "Ocean":
                return True
        return False
    
    def getLoc(self):
        return self._position
    
    def dump(self):
        troopdump = []
        for x in self.troops:
            troopdump.append(x.dumpToString())
        return dict(position=self._position, img=self._img, troops="".join(troopdump), owner=self._owner)
    
    @staticmethod
    def load(obj, sess):
        unit = Unit(
            loadCoordinates('Unit.position', obj.get('position')),
            loadString('Unit.img', obj.get('img')),
            sess,
            Troop.loadMultFromString(loadString('Unit.troops', obj.get('troops'))),
            loadString('Unit.owner', obj.get('owner')))
        return unit